package com.ksyun.campus.dataserver.config.dataserverconfig;

import com.ksyun.campus.dataserver.domain.DataServerInfo;
import com.ksyun.campus.dataserver.domain.ReplicaData;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Configuration
public class DataServerConfig {

    @Resource
    DataServerConfigProperties dataServerConfigProperties;

    /**
     * 添加用于存放当前活跃节点的集合对象
     *
     * @return 线程安全的ConcurrentHashMap（考虑到列表可能被多个事件集中回调，从而产生并发问题）
     */
    @Bean(name = "dataServerMap")
    public Map<String, DataServerInfo> getDataServerMap() {
        return new ConcurrentHashMap<>();
    }


    @PostConstruct
    private void prepareFilePath() {
        System.out.println(dataServerConfigProperties.getDataPath());
        File file = new File(dataServerConfigProperties.getDataPath());
        if (!file.exists()) {
            boolean rs = file.mkdirs();
            Assert.isTrue(rs, "数据保存路径创建异常, 请检查!");
        }
    }


    @Bean
    public RestTemplate addRestTemplate() {
        return new RestTemplate();

    }

    @Bean
    public DataServerInfo addDataServerInfo(DataServerConfigProperties dataServerConfigProperties, ServletWebServerApplicationContext webServerApplicationContext){
        InetAddress localHost;
        try {
            localHost = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        return new DataServerInfo(localHost.getHostAddress(), String.valueOf(webServerApplicationContext.getWebServer().getPort()), dataServerConfigProperties.getZone(), dataServerConfigProperties.getRack(),dataServerConfigProperties.getCapacity(), 0);

    }

    /**
     * 添加该节点上保存的文件副本信息，以fileNameId作为key
     * @return 线程安全的ConcurrentHashMap（考虑到列表可能被多个事件集中回调，从而产生并发问题）
     */
    @Bean(name = "ReplicaDataMap")
    public Map<String, ReplicaData> replicaDataMap(){
        return new ConcurrentHashMap<>();
    }
}
